import axios from "axios";
import { ElNotification } from "element-plus";
import { userStore } from '@/store/user.js'
import router from '@/router'
import { ElLoading } from 'element-plus'
const service = axios.create({
    baseURL: import.meta.env.VITE_BASE_URL,
    timeout: 40000,
});
console.log('import.meta.env.VITE_BASE_URL: ', import.meta.env.VITE_BASE_URL);

let loading = null
const closeLoading = () => {
    loading && loading.close()
    loading = false
}
//定义前置拦截器，请求拦截器，请求发送出去之前触发的
service.interceptors.request.use(
    (config) => {
        loading = ElLoading.service({
          lock: true,
          text: 'Loading',
          background: 'rgba(0, 0, 0, 0.7)',
        })
        //config 接口请求的配置信息
        const store = userStore()
        config.headers.Authorization = sessionStorage.getItem('BI_token') || ''
        return config;
    },
    (error) => {
        closeLoading()
        //报错的是时候抛出一个报错的信息
        return Promise.reject(error);
    }
);

//4. 定义后置拦截器,响应拦截器, 服务器响应回来数据之前触发，
service.interceptors.response.use(
    (response) => {
        closeLoading()
      console.log('response: ', response);
        //响应回来的数据操作
        const {
            status,
            data: {
              code,
              response: res,
              message, error
            },
        } = response;
        if (status === 200 && response.data instanceof Blob) {
            return response.data
        }
        if (code === 401 || code === 403) {
          console.log('router: ', router);
          const store = userStore()
          store.setToken('')
          store.setUserInfo({})
          window.localStorage.removeItem('BI_Menu')
          return router.replace({
            path: '/login'
          })
        }
        if (status === 200 && code === 200) {
            console.log('response: ', res);
            return res;
        }
        ElNotification({
            title: "提示",
            message: error || '请求失败,请检查网络',
            type: "warning",
        });
        return Promise.reject(error)
    },
    (error) => {
        closeLoading()
        //报错的是时候抛出一个报错的信息
        return Promise.reject(error);
    }
);
export default service;
